/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.server;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.sss.common.GetStatus;
import org.sss.common.InputDrivenTask;
import org.sss.common.TaskSliceSubmitter;
import org.sss.common.io.DataReader;
import org.sss.mapreduce.Configuration;
import org.sss.mapreduce.GroupID;
import org.sss.mapreduce.SssException;
import org.sss.mapreduce.StorageNode;
import org.sss.util.CallbackInterface;

public class CountTask extends Task implements InputDrivenTask<List<byte[]>> {
  private static Logger logger = SssServer.getLogger(CountTask.class);
  private final AtomicInteger readLatch;
  private CallbackInterface<GetStatus> doneCallback;
  private Throwable exception = null;

  private class DoNothingSliceSubmitter extends TaskSliceSubmitter<List<byte[]>> {
    public DoNothingSliceSubmitter() {
      super(getWKTP(), CountTask.this);
    }
    public void put(List<byte[]> data) throws SssException {
      /* Do nothing */
    }
  }

  public CountTask(UUID jobID,
                   SssServerResource sssResource,
                   Configuration conf,
                   StorageNode storageNode, GroupID input,
                   CallbackInterface<GetStatus> doneCallback) throws SssException {
    super(null, jobID, sssResource, conf, storageNode, new Input(input.getNonVolatileCopy()));
    this.doneCallback = doneCallback;
    this.readLatch  = new AtomicInteger(input.getNSlot());
  }

  public void submit() throws SssException {
    for (int i = 0; i < getInputGID().getNSlot(); ++i) {
      submitReadRequest(getIOManager().createDataReader(
            getConfiguration(), getStorageNode(), getInputGID(), i,
            new DoNothingSliceSubmitter()));
    }
  }

  /**
   * .
   * NOT CALLED.
   */
  @Override
  public void handle(List<byte[]> kvs) {
    throw new UnsupportedOperationException();
  }

  @Override
  public synchronized void noMoreTaskSlice(Throwable exp) {
    if (exp == null) {
      logger.debug("noMoreIORequestRead {}.", readLatch.get());
      if (readLatch.decrementAndGet() > 0) {
        return;
      }
      GetStatus s = new GetStatus();
      for (DataReader r: getDataReaders()) {
        s.inputTupleCount += r.getInputCount();
      }

      logger.debug("GetStatus.inputTupleCount {}.", s.inputTupleCount);

      doneCallback.callback(s);
    } else {
      logger.error("Error in CountTask", exp);
      errorCallback(exp);
    }
  }
  private synchronized void errorCallback(Throwable e) {
    if (exception == null) {
      GetStatus s = new GetStatus();
      s.exception = e;
      exception = e;

      doneCallback.callback(s);
    }
  }
}
